﻿// owner 蒋家伟

#include "DeviceManager.h"

// jsdk
#include "IDevice.h"
#include "Dbg_Warn_Define.h"

using namespace jsdk;

namespace
{
    static jsdk::DeviceManager s_DeviceManagerImp;
}

const IDevice * jsdk::DeviceManager::getDeviceByName(const std::wstring& deviceName) const
{
    const auto& iter = m_deviceClassToDevice.find(deviceName);
    if (iter != m_deviceClassToDevice.end())
    {
        return iter->second.get();
    }
    return nullptr;
}

IDevice * jsdk::DeviceManager::getDeviceFWByName(const std::wstring & deviceName)
{
    auto& iter = m_deviceClassToDevice.find(deviceName);
    if (iter != m_deviceClassToDevice.end())
    {
        return iter->second.get();
    }
    return nullptr;
}

void jsdk::DeviceManager::start() 
{
    for (auto& iter : m_deviceClassToDevice)
    {
        DBG_WARN_AND_CONTINUE_UNLESS(iter.second, L"设备管理器存在无效设备", L"蒋家伟", L"2023-07-31");
        iter.second->start();
    }
}

void jsdk::DeviceManager::stop() 
{
    for (auto& iter : m_deviceClassToDevice)
    {
        DBG_WARN_AND_CONTINUE_UNLESS(iter.second, L"设备管理器存在无效设备", L"蒋家伟", L"2023-07-31");
        iter.second->stop();
    }
}

jsdk::DeviceManager::~DeviceManager()
{

}

bool jsdk::DeviceManager::registerDevice(OwnerPtr<IDevice> opDevice)
{
    DBG_WARN_AND_RETURN_FALSE_UNLESS(opDevice, L"注册了一个无效设备", L"蒋家伟", L"2023-07-31");
    std::wstring name = opDevice->getDeviceName();
    DBG_WARN_AND_RETURN_FALSE_UNLESS(!name.empty(), L"设备名称无效", L"蒋家伟", L"2023-07-31");
    const auto& iter = m_deviceClassToDevice.find(name);
    if (iter != m_deviceClassToDevice.end())
    {
        DBG_WARN_AND_RETURN_FALSE_UNLESS(false, name + L"重复注册", L"蒋家伟", L"2023-07-31");
    }
    m_deviceClassToDevice[name].swap(opDevice);
    return true;
}

DeviceManager * jsdk::DeviceManager::getFW()
{
    return &s_DeviceManagerImp;
}

const DeviceManager * jsdk::DeviceManager::get()
{
    return &s_DeviceManagerImp;
}
